use model_graph_model::model::{default_model_name, get_model};
use model_graph_model::provider::get_provider;
use model_graph_types::container::workflow::CliStatementBuilder;
use model_graph_types::modeling::assistant::ModelType;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use model_graph_types::{
    container::workflow::{
        SpeechGeneratorStatement, WorkflowBlockExecuteResult, WorkflowBlockExecuteResultBuilder,
        WorkflowBlockExecuteResultStatus,
    },
    modeling::Value,
};

use crate::workflow::context::{Getter, WorkflowContext};

pub async fn execute(
    statement: &SpeechGeneratorStatement,
    context: Arc<Mutex<WorkflowContext>>,
) -> anyhow::Result<WorkflowBlockExecuteResult> {
    let result = _execute(statement, context).await;

    match result {
        Ok(v) => Ok(WorkflowBlockExecuteResultBuilder::default()
            .status(WorkflowBlockExecuteResultStatus::Succeeded)
            .source_handle("source")
            .result(v)
            .build()?),
        Err(err) => Ok(WorkflowBlockExecuteResultBuilder::default()
            .status(WorkflowBlockExecuteResultStatus::Succeeded)
            .source_handle("fail-branch")
            .build()?),
    }
}

pub async fn _execute(
    statement: &SpeechGeneratorStatement,
    context: Arc<Mutex<WorkflowContext>>,
) -> anyhow::Result<HashMap<String, Value>> {
    //默认的模型名称
    let (default_provider_name, default_model_name) = default_model_name(ModelType::TTS).await?;
    let model = &statement.model;

    //获取provider
    let provider_name = if &model.provider == "" {
        model.provider.clone()
    } else {
        default_provider_name
    };
    let (provider, provider_setting) = get_provider(&provider_name).await?;
    tracing::debug!("Provider:{:?}|{:?}", provider, provider_setting);

    let model_name = if let Some(model_name) = &model.name {
        //获取模型
        if let Ok((model, model_setting)) = get_model(model_name).await {
            tracing::debug!("Model:{:?}|{:?}", model, model_setting);
            model.name.clone()
        } else {
            model_name.clone()
        }
    } else {
        default_model_name
    };

    //
    let cli_statement = CliStatementBuilder::default()
        .current_dir("/Users/jinisu/Spark-TTS")
        .command(r#"echo test"#)
        .stderr(true)
        .stdout(true)
        .arguments(vec![])
        .build()?;

    let mut cli_result = crate::workflow::blocks::statements::cli::execute(&cli_statement, context)
        .await?
        .result;

    //
    Ok(cli_result)
}
